import axios from 'axios'
axios.defaults.baseURL = 'https://api.weixin.qq.com/'
import NProgress from 'nprogress'
import { Message } from 'element-ui'
export function request(config) {
  // 创建axios实例
  const instance = axios.create({
    baseURL: ''
  })

  // 请求拦截
  instance.interceptors.request.use(
    res => {
      // 展示进度条  NProgress.start()
      NProgress.start()
      return res
    },
    err => {
      console.log(err)
    }
  )

  // 响应拦截
  instance.interceptors.response.use(
    res => {
      // 隐藏进度条
      NProgress.done()
      return res.data
    },
    err => {
      console.log(err)
    }
  )
  // 发送网络请求
  return instance(config)
}
/*
 *@description: 封装获取token 在发送请求
 *@modifyContent:
 *@author: chendi
 *@date: 2020-08-17 15:38:37
*/
export async function encapsulation(option) {
  // 先获取tooken
  let token = await request({
    url: `/api/cgi-bin/token?grant_type=client_credential&appid=wx38373392939e805c&secret=c5b8c5d42ea638a695f51f3dabb3813a`,
    method: 'get'
  })
  console.info(token)
  if(token==undefined) {
    Message({
      message:  '网络连接失败，请尝试连接新的网络',
      type: 'error',
      duration: 5 * 1000
    })
    return 
  }
  console.info(token)
  // 为第二个请求 的url 添加token
  option.url = option.url + `?&access_token=${token.access_token}`
  // 添加云开发环境
  option.data['env']=`zhuma-mbnti`
  return await request(option)
}
